package com.proj.mhl.service;

import com.proj.mhl.dao.BillDAO;
import com.proj.mhl.dao.MultiTableBeanDAO;
import com.proj.mhl.domain.Bill;
import com.proj.mhl.domain.MultiTableBean;

import java.util.List;
import java.util.UUID;

public class BillService {
    BillDAO billDAO = new BillDAO();
    MenuService menuService = new MenuService();
    DiningTableService diningTableService = new DiningTableService();
    MultiTableBeanDAO multiTableBeanDAO = new MultiTableBeanDAO();
    //点餐方法
    public boolean OrderMenu(int menuId, int nums, int dingTableId) {
        //生成账单号,随机生成
        String billID = UUID.randomUUID().toString();
        //计算money
        double money = menuService.selectSingleMenu(menuId).getPrice() * nums;

        int update =
                billDAO.update("insert into bill values (null,?,?,?,?,?,now(),'未结账')", billID, menuId, nums, money, dingTableId);
        if (update <= 0) {
            return false;//插入新账单失败
        }
        //更新餐桌状态
        return diningTableService.updateDiningTableState(dingTableId, "就餐中");
    }

    //返回所有账单
    public List<MultiTableBean> list() {
        //return billDAO.queryMulti("select * from bill", Bill.class);
        return multiTableBeanDAO.queryMulti("select bill.*,name,price from bill,menu where bill.menuId = menu.id", MultiTableBean.class);
    }

    //某个餐桌是否有未结账账单
    public boolean hasPayBillByDiningTableId(int diningTableId) {
        Bill bill =
                billDAO.querySingle("select * from bill where diningTableId = ? and state = '未结账' limit 0,1", Bill.class, diningTableId);

        return (bill != null);
    }

    //完成结账 餐桌存在未结账账单
    public boolean payBill(int diningTableId, String payMode) {

        int update = billDAO.update("update bill set state = ? where diningTableId = ? and state = '未结账'", payMode, diningTableId);
        if (update <= 0) {//更新失败
            return false;
        }
        if (!(diningTableService.updateDiningTableStateToFree(diningTableId))) {
            return false;
        }
        return true;
    }
}
